package com.zaoke.web.service.food.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.time.DateUtils;

import com.zaoke.web.bo.food.FoodPromotion;
import com.zaoke.web.dao.food.FoodPromotionDao;
import com.zaoke.web.service.food.FoodPromotionService;
import com.zaoke.web.utils.LocalCaches;

@SuppressWarnings("unchecked")
public class FoodPromotionServiceImpl implements FoodPromotionService{
	
	private FoodPromotionDao foodPromotionDao;
	
	private long expireTime;

	public FoodPromotion getTodayPromotionByFoodId(long foodId) {
		Set<Long> foodIds = new HashSet<Long>();
		foodIds.add(foodId);
		Map<Long, FoodPromotion> promotions = getTodayPromotionByFoodIds(foodIds);
		if(promotions != null && promotions.containsKey(foodId))
			return promotions.get(foodId);
		return null;
	}

	public Map<Long, FoodPromotion> getTodayPromotionByFoodIds(Set<Long> ids) {
		Map<Long, FoodPromotion> result = new HashMap<Long, FoodPromotion>();
		
		List<FoodPromotion> promotions = getTodayAllPromotions();
		
		if(promotions != null && promotions.size() > 0)
			for(FoodPromotion promotion : promotions)
				if(promotion != null && DateUtils.isSameDay(promotion.getPromotionDate(), new Date()) && ids.contains(promotion.getFoodid()))
					result.put(promotion.getFoodid(), promotion);
		
		return result;
	}

	private List<FoodPromotion> getTodayAllPromotions() {
		List<FoodPromotion> promotions = (List<FoodPromotion>)LocalCaches.get(LocalCaches.ZAOKE_CACHE_TODAY_PROMOTIONS_KEY, System.currentTimeMillis(), expireTime);
		
		if(promotions == null){
			Date today = new Date();
			promotions = foodPromotionDao.getAllActivePromotionsByDates(DateUtils.truncate(today, Calendar.DATE), DateUtils.addMilliseconds(DateUtils.ceiling(today, Calendar.DATE), -1), new Integer[]{FoodPromotion.STATE_ACTIVE});
			
			if(promotions != null && promotions.size() > 0)
				LocalCaches.set(LocalCaches.ZAOKE_CACHE_TODAY_PROMOTIONS_KEY, promotions, System.currentTimeMillis());
		}
		
		return promotions;
	}

	public long getExpireTime() {
		return expireTime;
	}

	public void setExpireTime(long expireTime) {
		this.expireTime = expireTime;
	}

	public FoodPromotionDao getFoodPromotionDao() {
		return foodPromotionDao;
	}

	public void setFoodPromotionDao(FoodPromotionDao foodPromotionDao) {
		this.foodPromotionDao = foodPromotionDao;
	}
}
